use std::{
    net::{SocketAddr},
    sync::{
        atomic::{AtomicBool},
    },
};

use common::{base::id_generator, utils::time_utils};

use tokio::{
    io::{BufWriter},
    net::{tcp::OwnedWriteHalf},
};

pub struct Session {
    // 上一次接收信息的时间
    last_recv_timestamp: i64,
    //
    id: i64,
    // ip 地址
    ip: String,
    // 端口号
    port: u16,
    //
    is_active: bool, // 是否是主动连接
    // 连接信息
    conn_info: i64,

    is_close: AtomicBool,

    pub writer: BufWriter<OwnedWriteHalf>,
}

impl Session {
    pub fn new(
 
        addr: SocketAddr,
        is_active: bool,
        writer: OwnedWriteHalf,
    ) -> Box<Session> {
        let ip = addr.ip().to_string();
        let port = addr.port();

        let conn_info = id_generator::make_remote_node_id(&ip, port);
        Box::new(Session {
        
            last_recv_timestamp: 0,
            ip,
            is_close: AtomicBool::new(false),
            port,
            is_active,
            id: id_generator::gen_id(),
            conn_info,
            writer: BufWriter::new(writer),
        })
    }

    pub fn get_ip(&self) -> String {
        self.ip.clone()
    }

    pub fn get_conn_info(&self) -> i64 {
        self.conn_info
    }

    pub fn get_id(&self) -> i64 {
        self.id
    }

    pub fn get_port(&self) -> u16 {
        self.port
    }

    pub fn update_recv_timestamp(&mut self) {
        self.last_recv_timestamp = time_utils::cur_timestamp();
    }
}
